package com.lwl.concurrency.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by liwenlong on 2018/1/7 17:50
 */
public class CallableTest {
   static class FactorialCalculator implements Callable<Integer>{

       @Override
       public Integer call() throws Exception {
           int result = new Random().nextInt(100);
           TimeUnit.SECONDS.sleep(3);
           System.out.printf("%s : %d\n",Thread.currentThread().getName(),result);
           return result;
       }
   }

    public static void main(String[] args) {
        ThreadPoolExecutor executorService = (ThreadPoolExecutor)Executors.newFixedThreadPool(2);
        List<Future<Integer>> resultList = new ArrayList<>();
        FactorialCalculator calculator = new FactorialCalculator();

        for (int i = 0; i <10 ; i++) {
            Future<Integer> future = executorService.submit(calculator);
            resultList.add(future);
        }

        do {
            System.out.println("main: number of completed tasks: "+executorService.getCompletedTaskCount());
            for (int i = 0; i <resultList.size() ; i++) {
                Future<Integer> future = resultList.get(i);
                System.out.printf("main: task %d: %s\n",i,future.isDone());
            }
        }while (executorService.getCompletedTaskCount() < resultList.size());

        System.out.println("main:result");
        for (int i = 0; i < resultList.size(); i++) {
            Future<Integer> future = resultList.get(i);
            try {
                Integer integer = future.get();
                System.out.println(integer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService.shutdown();
    }




}
